package publish

import (
	"fmt"
	"gitee.com/fierce_wolf/go-fox-edge-common/commLogger"
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/Json"
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/Slice"
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/String"
	"gitee.com/fierce_wolf/go-fox-edge-iot-common/iotRemote"
	"go-fox-edge-iot-fox-publish/component"
	"strings"
)

type configEntityPublisher struct {
}

func (e *configEntityPublisher) publish(entityType string) {
	// 定义一个函数级的异常拦截，用来防止可能的代码BUG
	defer func() {
		if r := recover(); r != nil {
			commLogger.Console.Error(fmt.Sprintf("config() 捕获到异常:%v", r))
		}
	}()

	// 检查：是否到了执行的时间间隔
	ok, err := component.TimeIntervalService.TestLastTime(String.CamelName(entityType))
	if err != nil || !ok {
		return
	}

	// 弹出全部数据
	voList := component.RedisEntityService.QueryNotify(entityType)

	// 分拆为10个数据为一组
	lists := Slice.Split(voList, 5)

	// 分批发送
	topic := component.LocalConfig.Publish + "/" + strings.ToLower(entityType)
	for _, list := range lists {
		mapList := e.buildMapList(list)
		if len(mapList) == 0 {
			continue
		}

		body := Json.BuildJson(mapList)
		iotRemote.Mqtt.Publish(topic, body, 10*1000)
	}

}

func (e *configEntityPublisher) buildMapList(entityList []*component.EntityChangedNotifyVO) []map[string]interface{} {
	resultList := make([]map[string]interface{}, 0)

	for _, entityChangedNotifyVO := range entityList {
		if entityChangedNotifyVO.Key == "" {
			continue
		}

		result := entityChangedNotifyVO.BuildMap()

		resultList = append(resultList, result)
	}

	return resultList
}
